﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web.Caching;

namespace PwjCy.Lite.Common
{
    internal static class LiteCoreHelper
    {
        public static string StorageConfigPath = GetRootPath() + @"Config\Storage.config";
        public static string BootConfigPath = GetRootPath() + @"Config\Boot.config";
        public static string CacheConfigPath = GetRootPath() + @"Config\Cache.config";
        /// <summary>
        /// 获取程序根目录 .\
        /// </summary>
        /// <returns></returns>
        public static string GetRootPath()
        {
            string rootPath = AppDomain.CurrentDomain.BaseDirectory;
            int binPos = rootPath.IndexOf("bin");//找不到-1
            if (binPos < 0)
                return rootPath;
            return rootPath.Substring(0, binPos);
        }
        /// <summary>
        /// 获取Guid
        /// </summary>
        /// <returns></returns>
        public static string GetGuid()
        {
            return Guid.NewGuid().ToString().Replace("-", "");
        }
        /// <summary>
        /// 获取配置对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="configPath"></param>
        /// <returns></returns>
        public static T GetObjectSetting<T>(string configPath)
        {
            string key = typeof(T).FullName;
            if (null != LocalCacheHelper.Instance.GetCache<T>(key))
                return (T)HashCacheHelper.Instance.GetCache<T>(key);
            T objectSetting = XmlHelper.Instance.Deserizlize<T>(ReadFileContent(configPath));
            LocalCacheHelper.Instance.AddCacheDependency<T>(objectSetting, key, new CacheDependency(configPath));
            return objectSetting;
        }
        /// <summary>
        /// 读取文件文本
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static string ReadFileContent(string filePath)
        {
            string result = string.Empty;
            using (FileStream fs = new FileStream(filePath, FileMode.Open))
            {
                StreamReader m_streamReader = new StreamReader(fs);
                m_streamReader.BaseStream.Seek(0, SeekOrigin.Begin);//从数据流中读取每一行
                result = m_streamReader.ReadToEnd();
            }
            return result;
        }
    }
}
